<?php

declare (strict_types=1);

namespace App\Model;

/**
 * @property int $id
 * @property int $pid
 * @property string $name
 * @property string $path
 * @property string $title
 * @property string $type
 * @property string $menu_type
 * @property string $component
 * @property string $url
 * @property int $keepalive
 * @property int $status
 * @property int $sort
 * @property string $icon
 * @property int $update_time
 */
class AuthMenu extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'auth_menu';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'pid' => 'integer', 'keepalive' => 'integer', 'status' => 'integer', 'sort' => 'integer', 'update_time' => 'integer'];


    /**
     * 获取全部权限
     * @return array
     */
    public static function getAllMenuList()
    {

        $list = self::orderByDesc('sort')->get()->toArray();


        return self::buildTree($list);


    }


    /**
     * 更具角色组获取角色组的权限
     * @param $adminGroupId
     * @return array
     */
    public static function getMenuListByGroup($adminGroupId)
    {

        $power = AuthGroup::where(['id' => $adminGroupId, 'status' => 1])->value('power');

        $powerArray = explode(',', $power);

        $list = self::whereIn('id', $powerArray)->get()->toArray();

        return self::buildTree($list);

    }


    public function ownGroup()
    {
        return $this->belongsToMany(AuthGroup::class, 'auth_group_menu_ship');
    }


    public static function buildTree($data, $parentId = 0)
    {
        $tree = [];

        foreach ($data as $item) {
            if ($item['pid'] == $parentId) {
                $children = self::buildTree($data, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }

        return $tree;
    }


    /**
     * 获取所有下级 的id
     * @param $data
     * @param $parentId
     * @param array $descendants
     * @return array
     */
    public static function findSubIdS($data, $parentId, &$descendants = [])
    {

        foreach ($data as $item) {
            if ($item['pid'] == $parentId) {
                $descendants[] = $item['id'];
                self::findSubIdS($data, $item['id'], $descendants);
            }
        }
        return $descendants;
    }


}